<template>
  <view class="news">
    <Tabs
      :tabs="tabOptions"
      :modelValue="tabCurrent"
      @update:modelValue="onTabChange"
    />
    <template v-if="list.length">
      <view
        v-for="i of list"
        :key="i.id"
        class="news-item"
        hover-class="hover-default"
        @click="toDetail(i.id)"
      >
        <image class="cover-img" :src="i.img" mode="aspectFill" />
        <view class="cont flex flex-col justify-between">
          <view class="title">{{ i.title }}</view>
          <view class="desc">{{ i.sub_title }}</view>
          <view class="date-browse flex-row">
            <view class="date">{{ i.create_at }}</view>
            <view class="browse">{{ i.browse_count }}人阅读</view>
          </view>
        </view>
      </view>
      <uni-load-more icon-type="circle" :status="loadStatus" />
    </template>
    <view v-else class="no-data">暂无数据</view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onReachBottom } from '@dcloudio/uni-app'
import { useList } from '@/hooks/useList'
import { fetchNewsCategory, fetchNewsList } from '@/api'
import Tabs from '@/components/Tabs/index.vue'

const tabCurrent = ref(0)
const tabOptions = ref([])
const query = ref({
  cate_id: 0
})
const { list, loadStatus, getFirstList, getMoreList } = useList(
  fetchNewsList,
  query
)

fetchNewsCategory().then(res => {
  if (!Array.isArray(res) || res.length < 1) return
  tabOptions.value = res
  query.value.cate_id = res[0].id
  getFirstList()
})

onReachBottom(getMoreList)

function onTabChange(index) {
  uni.showLoading({
    title: '数据加载中...',
    mask: true
  })
  const tab = tabOptions.value[index]
  query.value.cate_id = tab.id
  getFirstList()
    .then(() => (tabCurrent.value = index))
    .finally(uni.hideLoading)
}

function toDetail(id) {
  uni.navigateTo({
    url: './details/index?id=' + id
  })
}
</script>

<style scoped lang="scss">
.news {
  display: flow-root;
  .news-item {
    margin: 30rpx;
    padding: 30rpx;
    border-radius: 16rpx;
    background-color: #fff;
    display: flex;
    column-gap: 22rpx;
    overflow: hidden;
    .cover-img {
      width: 220rpx;
      height: 160rpx;
      border-radius: 8rpx;
      flex-shrink: 0;
    }
    .cont {
      flex: 1;
      overflow: hidden;
      .title {
        color: #333;
        font-weight: bold;
        @include ellipsis(1);
      }
      .desc {
        color: #444;
        font-size: 26rpx;
        @include ellipsis(2);
      }
      .date-browse {
        width: 100%;
        color: #999;
        font-size: 22rpx;
      }
    }
  }
}
</style>
<style>
page {
  background-color: #f8f8f8;
}
</style>
